package pl.edu.agh.student.vrp.utils;

import java.util.LinkedList;
import java.util.List;
import org.jgap.Gene;
import org.jgap.IChromosome;
import org.jgap.impl.IntegerGene;

/**
 *
 * @author janburkot
 */
public class ChromosomeUtils
{
    
    public static List<Gene[]> getRoutes(IChromosome subject, int totalVehicles, int numberOfDestinations) {
        Gene[] genes = subject.getGenes();
        List<Integer> positions = new LinkedList<Integer>();

        for (int i = 0; i < genes.length; i++) {
            if (((IntegerGene) genes[i]).intValue() == 0) {
                positions.add(i);
                //System.out.println(i);
            }

        }

        //System.out.println("Positions: "+positions.size());
        List<Gene[]> routes = new LinkedList<Gene[]>();
        int i = 0;
        for (int j = 0; j < positions.size(); j++) {

            int k = positions.get(j);
            Gene[] genePart = new Gene[k - i];


            if (k - i > 0) {
                System.arraycopy(genes, i, genePart, 0, k - i);
                routes.add(genePart);
            }

            i = k + 1;

        }

        if (positions.get(positions.size() - 1) != (numberOfDestinations - 1 - 1 + totalVehicles)) {
            int k = numberOfDestinations - 1 - 1 + totalVehicles;
            i = positions.get(positions.size() - 1);

            //System.out.println("I: "+i);
            //System.out.println("K: "+k);
            
            Gene[] genePart = new Gene[k - i];

            System.arraycopy(genes, i + 1, genePart, 0, k - i);
            routes.add(genePart);
        }

        //System.out.println("Routes: "+routes.size());
        return routes;
    }
}
